package com.link.server.ws.handle.impl;

import com.link.common.packet.RequestOperate;
import com.link.common.packet.ResponseOperate;
import com.link.common.packet.resp.ChannelPacket;
import com.link.database.entity.DBChannel;
import com.link.database.service.DBChannelService;
import com.link.server.ws.handle.HandleComponent;
import com.link.server.ws.handle.Handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;

import java.util.List;

@HandleComponent(RequestOperate.LOAD_CHANNEL)
public class LoadChannelHandle implements Handler {
    @Resource
    private DBChannelService dbChannelService;
    @Override
    public   void invoke(RequestOperate operate, ByteBuf packet, ChannelHandlerContext ctx) throws  Exception{
        short regionId = packet.readShort();

        List<DBChannel> channels = dbChannelService.getChannelsByRegionId(regionId);
        List<ChannelPacket> list = channels.stream().map(it ->
                new ChannelPacket((short) it.getId(),
                        it.getChannelName(),
                        it.getServerIp(),
                        it.getServerPort(),
                        it.getStatus(),
                        it.getMaxOnline(),
                        it.getOnline()
                )
        ).toList();
        var bufferSize=list.stream().map(ChannelPacket::length).reduce(0, Integer::sum);
        ByteBuf  buffer = ctx.alloc().buffer(8+bufferSize);
         buffer.writeInt(ResponseOperate.LOAD_CHANNEL.code);
        buffer.writeInt(list.size());
        list.forEach(it->it.writeTo(buffer));

        this.send(ctx,buffer);


    }
}
